import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db';
import { orders, orderItems, cartItems } from '@/db/schema';
import { eq } from 'drizzle-orm';

export async function POST(request: NextRequest) {
  try {
    const { sessionId, customerEmail, customerName, shippingAddress, totalAmount } = await request.json();

    // 创建订单
    const [order] = await db.insert(orders).values({
      sessionId,
      totalAmount,
      customerEmail,
      customerName: `${customerName.firstName} ${customerName.lastName}`,
      shippingAddress: `${shippingAddress.address}, ${shippingAddress.city}, ${shippingAddress.zipCode}`,
      status: 'completed',
    }).returning();

    // 获取购物车商品
    const cartItemsData = await db
      .select()
      .from(cartItems)
      .where(eq(cartItems.sessionId, sessionId));

    // 创建订单商品
    for (const item of cartItemsData) {
      const product = await db.query.products.findFirst({
        where: (products, { eq }) => eq(products.id, item.productId),
      });

      if (product) {
        await db.insert(orderItems).values({
          orderId: order.id,
          productId: item.productId,
          productName: product.name,
          productPrice: product.price,
          quantity: item.quantity,
        });
      }
    }

    // 清空购物车
    await db.delete(cartItems).where(eq(cartItems.sessionId, sessionId));

    return NextResponse.json({ 
      success: true, 
      orderId: order.id 
    });
  } catch (error) {
    console.error('Failed to create order:', error);
    return NextResponse.json(
      { error: 'Failed to create order' },
      { status: 500 }
    );
  }
}

export async function GET(request: NextRequest) {
  try {
    const sessionId = request.nextUrl.searchParams.get('sessionId');
    
    if (!sessionId) {
      return NextResponse.json({ orders: [] });
    }

    const userOrders = await db
      .select()
      .from(orders)
      .where(eq(orders.sessionId, sessionId))
      .orderBy(orders.createdAt);

    // 获取每个订单的商品
    const ordersWithItems = await Promise.all(
      userOrders.map(async (order) => {
        const items = await db
          .select()
          .from(orderItems)
          .where(eq(orderItems.orderId, order.id));
        
        return {
          ...order,
          items
        };
      })
    );

    return NextResponse.json({ orders: ordersWithItems });
  } catch (error) {
    console.error('Failed to fetch orders:', error);
    return NextResponse.json(
      { error: 'Failed to fetch orders' },
      { status: 500 }
    );
  }
}